package com.example.projectmanagement.controller;

import com.example.projectmanagement.util.FileSecurityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/files")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class FileUploadController {

    @Value("${upload.path:uploads/}")
    private String uploadPath;

    /**
     * 上传文件（通用文件上传接口）
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 生成安全的文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.lastIndexOf(".") != -1) {
                extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            }
            
            // 验证文件扩展名
            if (!isValidFileExtension(extension)) {
                response.put("success", false);
                response.put("message", "只允许上传图片文件（jpg, jpeg, png）或视频文件（mp4, avi, mov, wmv）");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 根据文件类型设置不同的大小限制
            long maxSize = 10 * 1024 * 1024; // 默认10MB
            if (isVideoExtension(extension)) {
                maxSize = 1024 * 1024 * 1024; // 视频文件1GB
            }

            // 验证文件大小
            if (file.getSize() > maxSize) {
                String maxSizeStr = isVideoExtension(extension) ? "1GB" : "10MB";
                response.put("success", false);
                response.put("message", "文件大小不能超过" + maxSizeStr);
                return ResponseEntity.badRequest().body(response);
            }

            String safeFileName = UUID.randomUUID().toString() + extension;
            
            // 创建上传目录结构 - ensure it's absolute path
            String absoluteUploadPath = System.getProperty("user.dir") + "/" + uploadPath;
            String videoDirPath = absoluteUploadPath + "videos/";
            Path uploadDir = Paths.get(videoDirPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 构建文件保存路径
            Path filePath = uploadDir.resolve(safeFileName);
            
            // 保存文件
            file.transferTo(filePath.toFile());

            // 返回成功响应
            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("fileName", safeFileName);
            response.put("filePath", filePath.toString());
            response.put("url", "/api/files/download/" + safeFileName);
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "文件上传异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 上传课程封面图片
     */
    @PostMapping("/upload-course-cover")
    public ResponseEntity<Map<String, Object>> uploadCourseCover(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证文件大小（最大10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                response.put("success", false);
                response.put("message", "文件大小不能超过10MB");
                return ResponseEntity.badRequest().body(response);
            }

            // 生成安全的文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.lastIndexOf(".") != -1) {
                extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            }
            
            // 验证文件扩展名
            if (!isValidFileExtension(extension)) {
                response.put("success", false);
                response.put("message", "只允许上传图片文件（jpg, jpeg, png）或视频文件（mp4, avi, mov, wmv）");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 根据文件类型设置不同的大小限制
            long maxSize = 10 * 1024 * 1024; // 默认10MB
            if (isVideoExtension(extension)) {
                maxSize = 1024 * 1024 * 1024; // 视频文件1GB
            }

            // 验证文件大小
            if (file.getSize() > maxSize) {
                String maxSizeStr = isVideoExtension(extension) ? "1GB" : "10MB";
                response.put("success", false);
                response.put("message", "文件大小不能超过" + maxSizeStr);
                return ResponseEntity.badRequest().body(response);
            }

            String safeFileName = "course_cover_" + UUID.randomUUID().toString() + extension;
            
            // 创建上传目录（如果不存在），改为courseCover子目录
            // 使用项目根目录的绝对路径确保可靠性
            String absoluteUploadPath = System.getProperty("user.dir") + "/" + uploadPath + "courseCover/";
            Path uploadDir = Paths.get(absoluteUploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 构建文件保存路径
            Path filePath = uploadDir.resolve(safeFileName);
            
            // 保存文件
            file.transferTo(filePath.toFile());

            // 返回成功响应
            response.put("success", true);
            response.put("message", "课程封面上传成功");
            response.put("fileName", safeFileName);
            response.put("filePath", filePath.toString());
            response.put("url", "/api/files/download/" + safeFileName);
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "课程封面上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "课程封面上传异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{fileName}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {
        try {
            // 验证文件名安全性
            // 为了兼容不同类型的文件，我们放宽验证条件
            if (fileName == null || fileName.isEmpty() || fileName.contains("..")) {
                return ResponseEntity.badRequest().build();
            }
            
            // 构造完整的文件路径（优先检查courseCover目录）
            Path filePath = null;
            Path courseCoverPath = Paths.get(System.getProperty("user.dir") + "/" + uploadPath + "courseCover/", fileName);
            if (Files.exists(courseCoverPath)) {
                filePath = courseCoverPath;
            } else {
                // 如果是视频文件，检查特定课程目录
                Path videoPath = Paths.get(System.getProperty("user.dir") + "/" + uploadPath + "videos/", fileName);
                if (Files.exists(videoPath)) {
                    filePath = videoPath;
                } else {
                    // 如果不在特定目录，则使用默认路径
                    filePath = Paths.get(uploadPath, fileName);
                }
            }
            
            // 安全检查：确保文件在允许的目录中
            Path normalizedPath = filePath.normalize();
            // 更严格的路径检查，确保文件路径在项目根目录内
            Path projectDirPath = Paths.get(System.getProperty("user.dir")).toAbsolutePath().normalize();
            
            // 确保路径在项目目录内
            if (!normalizedPath.startsWith(projectDirPath)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }
            
            byte[] fileBytes = Files.readAllBytes(filePath);
            return ResponseEntity.ok()
                    .header("Content-Disposition", "inline; filename=\"" + fileName + "\"")
                    .body(fileBytes);
                    
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 验证是否为允许的文件扩展名（图片或视频）
     */
    private boolean isValidFileExtension(String extension) {
        if (extension == null) return false;
        // 允许图片文件
        if (".jpg".equals(extension) || ".jpeg".equals(extension) || ".png".equals(extension)) {
            return true;
        }
        // 允许视频文件
        if (".mp4".equals(extension) || ".avi".equals(extension) || ".mov".equals(extension) || ".wmv".equals(extension)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为视频文件扩展名
     */
    private boolean isVideoExtension(String extension) {
        if (extension == null) return false;
        return ".mp4".equals(extension) || ".avi".equals(extension) || ".mov".equals(extension) || ".wmv".equals(extension);
    }
}